let storage = weex.requireModule('storage')
let Deferred = require('Deferred')
module.exports = {
  setItem (key, value) {
    var deferred = new Deferred()
    value = JSON.stringify(value)
    storage.setItem(key, value, rs => {
      deferred.resolve(rs)
    })
    return deferred.promise()
  },
  getItem (key, defaultVal) {
    var deferred = new Deferred()
    storage.getItem(key, rs => {
      if (rs.result === 'failed') {
        deferred.resolve(null || defaultVal, rs)
      } else {
        try {
          deferred.resolve(JSON.parse(rs.data), rs)
        } catch (e) {
          deferred.resolve(null || defaultVal, rs)
        }
      }
    })
    return deferred.promise()
  },
  removeItem (key) {
    var deferred = new Deferred()
    storage.removeItem(key, rs => {
      deferred.resolve(rs)
    })
    return deferred.promise()
  },
  length () {
    var deferred = new Deferred()
    storage.length(rs => {
      deferred.resolve(rs.data, rs)
    })
    return deferred.promise()
  },
  getAllKeys (callback) {
    var deferred = new Deferred()
    storage.length(rs => {
      deferred.resolve(rs.data, rs)
    })
    return deferred.promise()
  }
}
